package nature.nano.control.script.parse;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;

import nature.nano.component.EmptyProps;
import nature.nano.component.SimpleProps;
import nature.nano.component.Strings;
import nature.nano.iface.Accepter;
import nature.nano.component.PrimaryProvider;

public class ScriptFileReader extends PrimaryProvider {

	public ScriptFileReader() {
		props(Strings.file);		
	}
	
	@Override
	public void start() {
		String file = prop(Strings.file);
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
		} catch (Exception e) {
			SimpleProps props = new SimpleProps(Strings.errorType, Strings.readFileFailed, Strings.exception, e.toString());
			slot(Strings.error).onBegin(Strings.error, props);
			slot(Strings.error).onEnd(Strings.error);
			return;
		}
		
		Accepter accepter = slot(Strings.output);
		accepter.onBegin(Strings.root, EmptyProps.instance);
		
		String buffer = null;
		int index = 0;
		do {
			try {
				buffer = reader.readLine();
			} catch (IOException e) {
				SimpleProps props = new SimpleProps(Strings.errorType, Strings.readRowFailed, Strings.exception, e.toString());
				slot(Strings.error).onBegin(Strings.error, props);
				slot(Strings.error).onEnd(Strings.error);
				break;
			}
			if (buffer == null) {
				break;
			}
			
			accepter.onBegin(Strings.row, new SimpleProps(Strings.index, Integer.toString(index)));
			accepter.onContent(buffer.trim());
			accepter.onEnd(Strings.row);
			index++;
		} while (true);

		accepter.onEnd(Strings.root);
	}

}
